<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\Register;
use App\Http\Requests\Login;
use App\Models\User;
use App\Models\Wallet;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
use Validator;
use App\Events\UserRegistered;



class IndexController extends Controller
{
    //登录
    public function login()
    {
        
        return view('home.index.login');
    }
    /**
     * 登录
     *
     * @param Request $request
     * @return void
     */
    public function login_check(Login $request)
    {
        $user=User::where('phone', $request->phone)->first();
        if (!Hash::check($request->password, $user->password)) {
            return redirect('/login')->with(['code'=>2,'msg'=>'密码错误']);
        }
        if ($user->status==2) {
            return redirect('/login')->with(['code'=>2,'msg'=>'您的账号已被封停']);
        }
        $request->session()->put('uid', $user->id);
        // session(['user_id'=>$user->id]);
        return redirect('/center/index')->with(['code'=>0,'msg'=>'登录成功'])->cookie('uid',$user->id);
    }

    //注册
    public function register(Request $request)
    {
        if (!$request->code) {
            $request->code='';
        }
        return view('home.index.register')->with('code', $request->code);
    }

    public function register_make(Register $request)
    {
        
        $check_sms = $this->checkSmsCode(request('phone'), request('sms_code'), 1);
        if ($check_sms !== true) {
            return redirect("/register/{$request->register_code}")->with(['code'=>2,'msg'=>$check_sms['message']]);
        }

        $user_code = $request->register_code; //推荐人code
        $recommend_user = User::where('register_code', $user_code)->first();

        if (!$recommend_user) {
            $pid=0;
        } else {
            $pid=$recommend_user->id;
        }

        $password = bcrypt($request->password);
        $sec_password = bcrypt($request->sec_password);
        $register_code=$this->get_code();
        
        $data = [
            'phone' => $request->phone,
            'password' => $password,
            'sec_password' => $sec_password,
            'pid' => $pid,
            'status' => 1,
            'register_code' => $register_code
        ];

        DB::beginTransaction();
        try {
            $user_id = User::insertGetId($data);
            event(new UserRegistered($user_id));

            Wallet::insert(['user_id' => $user_id]);
            DB::commit();
        } catch (QueryException $ex) {
            DB::rollback();
            return redirect("/register/{$request->code}")->with(['code'=>2,'msg'=>'注册失败']);
        }
        return redirect('/register')->with(['code'=>1,'msg'=>'注册成功']);
    }
    //获取邀请码
    public function get_code()
    {
        $code = mt_rand(100000, 999999);
        $user = User::where('register_code', $code)->first();
        if (!$user) {
            return strtolower($code);
        } else {
            return $this->get_code();
        }
    }
    //忘记密码
    public function forget()
    {
        return view('home.index.forget');
    }

    public function forget_make(Request $request)
    {
        $this->validate(
            $request,
            [
                'phone' => ['required','exists:users,phone','regex:/^((13[0-9])|(15[^4])|(166)|(17[0-8])|(18[0-9])|(19[8-9])|(147)|(145))\\d{8}$/'],
                'password' => 'required|confirmed',
                'sms_code' => 'required',
            ],
            [
                'phone.required' => '请输入手机号',
                'phone.exists' => '没有该用户，请先注册',
                'phone.regex' => '手机号格式错误',

                'password.required' => '请输入密码',
                'password.confirmed' => '密码和确认密码不一致',
                'sms_code' => '请输入手机邀请码',
            ]
        );

        $check_sms = $this->checkSmsCode($request->phone, $request->sms_code, 2);
        if ($check_sms !== true) {
            return redirect('/forget')->with(['code'=>2,'message'=>$check_sms['message']]);
        }
        $password = bcrypt($request->password);
        $data=[
            'password'=>$password,
        ];
        $user=User::where('phone', $request->phone)->update($data);

        if (!$user) {
            return redirect('/forget')->with(['code'=>2,'message'=>'修改失败']);
        }
        return redirect('/login')->with(['code'=>2,'message'=>'修改成功']);
    }
    public function test()
    {
        event(new UserRegistered(1));
    }
}
